//
//  LHXCutImageViewController.m
//  Etwo
//
//  Created by 林浩翔 on 16/6/17.
//  Copyright © 2016年 林浩翔. All rights reserved.
//

#import "LHXCutImageViewController.h"
#import "LHXCutImageView.h"
#import "LHXBtnMenusViewController.h"
#import "LHXMainBtnItem.h"
#import "LHXBtnItem.h"




@interface LHXCutImageViewController ()

/**暂时存放裁前的图片*/
@property (strong, nonatomic)UIImage *beforeCutImage;
/**手指开始的点*/
@property (assign,nonatomic)CGPoint startP;
/**遮罩*/
@property (weak,nonatomic)UIView *cover;
/**遮罩*/
@property (weak,nonatomic)UIView *coverView;
/**裁剪后的图片*/
@property (weak,nonatomic)UIScrollView *NewImageScrollView;
/**图形上下文第一层图片*/
@property (strong,nonatomic)UIImage *fristImage;
/**裁剪图片后的按钮数组*/
@property (strong,nonatomic)NSMutableArray *cutBtnArray;
/**保存按钮*/
@property (weak,nonatomic)LHXbutton *saveBtn;
/**裁剪按钮View*/
@property (weak,nonatomic)UIView *cutBtnView;
/**裁剪按钮标题*/
@property (strong,nonatomic)NSArray *cutBtnTitleArray;
/**裁剪后的图标初始frame*/
@property (assign,nonatomic)CGRect newImageViewFrame;
/**手指开始的点*/
@property (assign,nonatomic)CGPoint tempP;








@end

@implementation LHXCutImageViewController

#pragma mark --懒加载

- (NSMutableArray *)cutBtnArray{
    if (_cutBtnArray == nil) {
        _cutBtnArray = [NSMutableArray array];
    }
    return _cutBtnArray;
}

- (NSArray *)cutBtnTitleArray{
    if (_cutBtnTitleArray == nil) {
        _cutBtnTitleArray = @[@"返回",@"确定"];
    }
    return _cutBtnTitleArray;
}

- (NSArray *)btnItemArray{
    if (_btnItemArray == nil) {
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"MainBtn" ofType:@"plist"];
        NSArray *BtnItemArray = [NSArray arrayWithContentsOfFile:plistPath];
        LHXMainBtnItem *MainItem = [LHXMainBtnItem MainItemWithArray:BtnItemArray];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dict in MainItem.CutImageViewBtnItem) { // 遍历字典数组中的每一个字典
            // 将字典 转为 模型
            LHXBtnItem *btnItem = [LHXBtnItem itemWithDict:dict];
            
            [tempArray addObject:btnItem];
        }
        _btnItemArray = tempArray;
        
    }
    return _btnItemArray;
}

-(UIView *)coverView{
    if (_coverView == nil) {
        UIView *coverView = [[UIView alloc]init];
        coverView.backgroundColor = [UIColor clearColor];
        self.coverView = coverView;
        [self.view addSubview:self.coverView];

    }
    return _coverView;
}

- (UIView *)cover{
    if (_cover == nil) {
        
        UIView *cover = [[UIView alloc]init];
        cover.backgroundColor = [UIColor whiteColor];
        cover.alpha = 0.5;
        _cover = cover;
        [self.coverView addSubview:cover];
    }
    return _cover;
}


#pragma mark --view生命周期
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self addPan];
    
    [self addPinch];
  
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
   

}

#pragma mark --按钮点击事件
- (void)BtnClick:(LHXbutton *)btn{
    
    [LHXchoose shareChoose].cutImageView = self.cutImageView;
    [LHXchoose shareChoose].chooseImage = self.cutImageView.image;
    
        
        if ([btn.btnTextTag isEqualToString:@"菜单"]) {
            
            [[LHXchoose shareChoose].cutImageView removeGestureRecognizer:[LHXchoose shareChoose].cutImageView.pinch];
            
            [LHXchoose shareChoose].cutImageView.pinch = nil;
            
            
            LHXBtnMenusViewController *menusVC = [[LHXBtnMenusViewController alloc]init];
            
            menusVC.disenbleBtnName = @"裁剪工具";
            
            menusVC.transitioningDelegate = self;
            
            menusVC.modalPresentationStyle = UIModalPresentationCustom;
            
            [self presentViewController:menusVC animated:YES completion:nil];
            

        }else if([btn.btnTextTag isEqualToString:@"重新选图"]){
            [self getPicture];
        }else if([btn.btnTextTag isEqualToString:@"裁剪"]){
            self.btnScrollView.hidden = YES;
            
            [self.cutImageView removeGestureRecognizer:self.cutImageView.tap];
            
            [self addPanForImageView];
        }else if ([btn.btnTextTag isEqualToString:@"保存"]){
            [self creadAlertWithTitle:nil andMessage:@"确定要保存图片吗?"];

        }else if([btn.btnTextTag isEqualToString:@"全屏截图"]){
            [self fullScreenCutImage];
        }
        

}
/**保存图片后执行的操作*/
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    NSLog(@"保存成功");
}

/**全屏截图*/
- (void)fullScreenCutImage{
    
    UIGraphicsBeginImageContextWithOptions([UIScreen mainScreen].bounds.size, NO, 0.0);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [self.mainmainView.layer renderInContext:ctx];
    
    UIImage *FullImage = UIGraphicsGetImageFromCurrentImageContext();
    
    [self.cutImageView removeFromSuperview];
    
    LHXCutImageView *FullImageV = [LHXCutImageView cutImageWith:FullImage];
    
    self.cutImageView = FullImageV;
    
    [self addPan];
    
    [self addPinch];
    
    [self.mainView addSubview:self.cutImageView];
    
    //创建弹窗
    [self creadAlertWithTitle:@"截图成功" andMessage:@"是否保存到相册?"];
}

- (void)cutClick:(LHXbutton *)btn{
    
    [self.view removeGestureRecognizer:self.cutImageView.pan];
    
    if ([btn.btnTitle.text isEqualToString:@"确定"]) { //确定
        
        CGRect coverF = self.NewImageScrollView.frame;
        
        CGRect cutRect = CGRectMake(coverF.origin.x * self.fristImage.scale, coverF.origin.y * self.fristImage.scale, coverF.size.width * self.fristImage.scale, coverF.size.height * self.fristImage.scale);
        
        //根据cutRect裁剪图片
        CGImageRef imageRef = CGImageCreateWithImageInRect(self.fristImage.CGImage, cutRect);
        
        UIImage *afterCutImage = [UIImage imageWithCGImage:imageRef];
        //删除旧的图片
        [self.cutImageView removeFromSuperview];
        
        LHXCutImageView *newImageView = [LHXCutImageView cutImageWith:afterCutImage];
        
        self.cutImageView = newImageView;
        
        [LHXchoose shareChoose].cutImageView = newImageView;
        
        [self.mainView addSubview:self.cutImageView];
        
        [self.NewImageScrollView removeFromSuperview];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LHXeditImage" object:self];
        
    }else if([btn.btnTitle.text isEqualToString:@"返回"]){
        
        [self.NewImageScrollView removeFromSuperview];
        
        [self.cutImageView removeFromSuperview];

        LHXCutImageView *newImageView = [LHXchoose shareChoose].cutImageView;
        
        [self.mainView addSubview:newImageView];
        
        self.cutImageView = newImageView;
        
        [self.cutImageView removeGestureRecognizer:self.cutImageView.pan];
        
    }
    
    [self setButton];
    
    [self showButtonAnimation];
    
    [self addPan];
    
    [self addPinch];
    
    self.cutBtnView.hidden = YES;
    
    [self.cutBtnView removeFromSuperview];
}




/**创建弹窗(点确定保存到系统相册)*/
- (void)creadAlertWithTitle:(NSString *)title andMessage:(NSString *)message{
    //创建弹窗
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *SaveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImageWriteToSavedPhotosAlbum(self.cutImageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
    
    UIAlertAction *CancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"LHXeditImage" object:self];
    }];
    
    [AlertController addAction:CancelAction];
    
    [AlertController addAction:SaveAction];
    
    
    [self presentViewController:AlertController animated:YES completion:nil];
}

/**给cutImageView添加手势*/
- (void)addPanForImageView{

    //删除pinch滑动手势
    [self.mainView removeGestureRecognizer:self.cutImageView.pinch];
    
    //删除pan滑动手势
    [self.cutImageView removeGestureRecognizer:self.cutImageView.pan];
    
    UIPanGestureRecognizer *panCut = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panCut:)];
    
    self.cutImageView.pan = panCut;
    
    [self.cutImageView addGestureRecognizer:panCut];
    
}

#pragma mark -- pan裁剪手势
- (void)panCut:(UIPanGestureRecognizer *)pan{
    //获取手指的点
    
    CGPoint curP = [pan locationInView:self.mainView];
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        self.startP = curP;
    
        UIGraphicsBeginImageContextWithOptions([UIScreen mainScreen].bounds.size, NO, 0.0);
        
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        
        [self.mainView.layer renderInContext:ctx];
        
        UIImage *fristImage = UIGraphicsGetImageFromCurrentImageContext();
        
        self.fristImage = fristImage;
        
        UIGraphicsEndPDFContext();


    }else if (pan.state == UIGestureRecognizerStateChanged){
        
        if (curP.x > CGRectGetMaxX(self.cutImageView.frame)) {
            curP.x = CGRectGetMaxX(self.cutImageView.frame);
        }
        if (curP.x < self.cutImageView.frame.origin.x) {
            curP.x = self.cutImageView.frame.origin.x;
        }
        if (curP.y >  CGRectGetMaxY(self.cutImageView.frame)) {
            curP.y= CGRectGetMaxY(self.cutImageView.frame);
        }
        if (curP.y < self.cutImageView.frame.origin.y) {
            curP.y = self.cutImageView.frame.origin.y;
        }
        
        CGFloat coverW = curP.x - self.startP.x;
        CGFloat coverH = curP.y - self.startP.y;
        
        CGRect coverRect = CGRectMake(self.startP.x, self.startP.y, coverW, coverH);
        self.coverView.frame = coverRect;
        self.cover.frame = CGRectMake(0, 0, self.coverView.frame.size.width, self.coverView.frame.size.height);
        
        
    }else if(pan.state == UIGestureRecognizerStateEnded){
        
        [LHXchoose shareChoose].cutImageView = self.cutImageView;
        
        //第一层:原图
        UIGraphicsBeginImageContextWithOptions([UIScreen mainScreen].bounds.size, NO, 0.0);
        
        CGContextRef ctx = UIGraphicsGetCurrentContext();

        [self.mainView.layer renderInContext:ctx];
        
        UIImage *midImage = UIGraphicsGetImageFromCurrentImageContext();
        
        //第二层:透明黑遮罩
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.mainView.bounds];
        
        [[UIColor colorWithWhite:0 alpha:0.7]set];
        
        [path fill];
        
        //获取第二层渲染图片
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        //关闭上下文
        UIGraphicsEndPDFContext();
        
        //将原来显示的图片设置为半透明黑色样式
        [self.cutImageView removeFromSuperview];
        
        LHXCutImageView *newImageView = [LHXCutImageView cutImageWith:newImage];
        
        self.cutImageView = newImageView;
        
        [self.mainView addSubview:newImageView];
        
        
        //第三层
        
        UIScrollView *newImageScrollView = [[UIScrollView alloc]initWithFrame:self.coverView.frame];
        
        newImageScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
        
        newImageScrollView.scrollEnabled = NO;
        
        newImageScrollView.showsHorizontalScrollIndicator = NO;
        
        newImageScrollView.showsVerticalScrollIndicator = NO;
        
        UIImageView *midImageView = [[UIImageView alloc]initWithImage:midImage];
        
        newImageScrollView.backgroundColor = [UIColor clearColor];
        
        [newImageScrollView addSubview:midImageView];
        
        newImageScrollView.contentOffset = CGPointMake( self.coverView.frame.origin.x,  self.coverView.frame.origin.y);
        
        self.NewImageScrollView = newImageScrollView;
        
        [self.mainView addSubview:newImageScrollView];
        
//        //删除屏幕上的遮罩
        [self.cover removeFromSuperview];
        
        [self.coverView removeFromSuperview];

//        //给后方的图片删除pan手势
        [self.cutImageView removeGestureRecognizer:pan];
        
        [self setAfterCutBtn];
        
        self.newImageViewFrame = self.NewImageScrollView.frame;
        
        UIPanGestureRecognizer *panMove = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMoveCover:)];
        
        self.cutImageView.pan = panMove;
        
        [self.view addGestureRecognizer:panMove];
    }
    

}

/**移动遮罩*/
- (void)panMoveCover:(UIPanGestureRecognizer *)pan{
    //获取手指的点
    CGPoint curP = [pan locationInView:self.mainView];
    
    //拿到NewImageV的四个方位矩阵
    //左上角
    CGRect coverTopLight = CGRectMake(self.NewImageScrollView.frame.origin.x - 20, self.NewImageScrollView.frame.origin.y - 20, 40, 40);
    //右上角
    CGRect coverTopRight = CGRectMake(CGRectGetMaxX(self.NewImageScrollView.frame) - 20, self.NewImageScrollView.frame.origin.y - 20, 40, 40);
    //右下角
    CGRect coverBottomRight = CGRectMake(CGRectGetMaxX(self.NewImageScrollView.frame) - 20, CGRectGetMaxY(self.NewImageScrollView.frame) - 20, 40, 40);
    //左下角
    CGRect coverBottomLight = CGRectMake(self.NewImageScrollView.frame.origin.x - 20, CGRectGetMaxY(self.NewImageScrollView.frame) - 20, 40, 40);
    
    CGRect newImageF = self.NewImageScrollView.frame;
    if (pan.state == UIGestureRecognizerStateBegan) {
        self.startP = curP;
        
        
    }else if(pan.state == UIGestureRecognizerStateChanged){
        
        //设置最小宽高
        if(self.NewImageScrollView.frame.size.width < 50 ){
            newImageF.size.width = 49.9;
            
            self.NewImageScrollView.frame = newImageF;
            return;
            
        }
        
        if(self.NewImageScrollView.frame.size.height < 50){
            newImageF.size.height = 49.9;
            
            self.NewImageScrollView.frame = newImageF;
            return;
            
        }
        //如果手指的店在左上角
        if(CGRectContainsPoint(coverTopLight, self.startP)){
            newImageF.size.width = self.newImageViewFrame.size.width + (self.newImageViewFrame.origin.x - curP.x);
            newImageF.size.height = self.newImageViewFrame.size.height + (self.newImageViewFrame.origin.y - curP.y);
            newImageF.origin.x = curP.x;
            newImageF.origin.y = curP.y;
            
            self.NewImageScrollView.contentOffset = CGPointMake(curP.x, curP.y);
            
        }else if(CGRectContainsPoint(coverTopRight, self.startP)){
            //如果手指的点在右上角
            newImageF.origin.y = curP.y;
            newImageF.size.width = self.newImageViewFrame.size.width + (curP.x - CGRectGetMaxX(self.newImageViewFrame));
            newImageF.size.height = self.newImageViewFrame.size.height + (self.newImageViewFrame.origin.y - curP.y);
            
            self.NewImageScrollView.contentOffset = CGPointMake(self.NewImageScrollView.frame.origin.x, curP.y);

        }else if(CGRectContainsPoint(coverBottomLight, self.startP)){
            //如果手指的点在左下角
            newImageF.origin.x = curP.x;
            newImageF.size.width = self.newImageViewFrame.size.width + (self.newImageViewFrame.origin.x - curP.x);
            newImageF.size.height = self.newImageViewFrame.size.height + (curP.y - CGRectGetMaxY(self.newImageViewFrame));
            self.NewImageScrollView.contentOffset = CGPointMake(curP.x, self.NewImageScrollView.frame.origin.y);

            
            

        }else if(CGRectContainsPoint(coverBottomRight, self.startP)){
            //如果手指的点在右下角
            newImageF.size.width = self.newImageViewFrame.size.width + (curP.x - CGRectGetMaxX(self.newImageViewFrame));
            newImageF.size.height = self.newImageViewFrame.size.height + (curP.y - CGRectGetMaxY(self.newImageViewFrame));
            
            
        }

        self.startP = curP;
        self.NewImageScrollView.frame = newImageF;
        
    }if (pan.state == UIGestureRecognizerStateEnded) {
        
        if(self.NewImageScrollView.frame.size.width < 50 ){
            newImageF.size.width = 50;
            
                self.NewImageScrollView.frame = newImageF;

            
        }
        
        if(self.NewImageScrollView.frame.size.height < 50){
            newImageF.size.height = 50;
                self.NewImageScrollView.frame = newImageF;
                
            
        }
        
        
        self.newImageViewFrame = self.NewImageScrollView.frame;
        
        
    }

        
        


    
}

#pragma mark --设置点击裁剪之后的按钮
- (void)setAfterCutBtn{
    
    UIView *cutBtnView = [[UIView alloc]init];
    
    cutBtnView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - btnWH - 30, [UIScreen mainScreen].bounds.size.width, btnWH + 20);
        
    self.cutBtnView = cutBtnView;
    
    [self.view addSubview:cutBtnView];
    
    CGFloat btnSpace = ([UIScreen mainScreen].bounds.size.width - (self.cutBtnTitleArray.count * btnWH))/ (self.cutBtnTitleArray.count + 1) ;
    
    
    for (int i = 0; i < self.cutBtnTitleArray.count; i++) {
        LHXbutton *btn = [LHXbutton btn];
        
        btn.frame = CGRectMake(btnSpace + ((btnWH + btnSpace) * i), 10, btnWH, btnWH);
        
        btn.btnTitle.text = self.cutBtnTitleArray[i];
        
        btn.tag = i;
                
        [btn setBackgroundImage:[UIImage imageNamed:@"cutImageView_backgroundColor"] forState:UIControlStateNormal];
        
        [btn setBackgroundImage:[UIImage imageNamed:@"cutImageView_BtnHighlight"] forState:UIControlStateHighlighted];
        
        [btn addTarget:self action:@selector(cutClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.cutBtnView addSubview:btn];
        
        [self.cutBtnArray addObject:btn];
    }

}


//添加滑动手势
- (void)addPan{
    if(self.cutImageView.pan == nil){
        //创建手势
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self.cutImageView action:@selector(pan:)];
        
        self.cutImageView.pan = pan;
        //添加手势
        [self.cutImageView addGestureRecognizer:pan];
    }
    
    
}
//添加捏合手势
- (void)addPinch{
    
    if (self.cutImageView.pinch == nil) {
        //添加捏合手势
        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self.cutImageView action:@selector(pinch:)];
        
        pinch.delegate = self.cutImageView;
        
        self.cutImageView.pinch = pinch;
        
        [self.mainView addGestureRecognizer:pinch];
    }
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
